package com.atguigu.Serivce.Impl;

import com.atguigu.GlobalExceptionHandler.CustomException;
import com.atguigu.Serivce.*;
import com.atguigu.Utils.BaseContext;
import com.atguigu.Utils.R;
import com.atguigu.mapper.OrdersMapper;
import com.atguigu.mapper.UserMapper;
import com.atguigu.pojo.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders>implements OrdersService {

   @Autowired
   private OrdersMapper ordersMapper;

   @Autowired
   private OrderDetailService orderDetailService;

   @Autowired
   private ShoppingCartService shoppingCartService;

   @Autowired
   private UserMapper userMapper;

   @Autowired
   private AddressBookService addressBookService;

   @Transactional
    @Override
    public R submit(Orders orders) {//支付
        //1.获得当前用户
       Long currentId = BaseContext.getCurrentId();

       //2.获得当前用户的购物车数据
       LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
       queryWrapper.eq(ShoppingCart::getUserId, currentId);
       List<ShoppingCart> list = shoppingCartService.list(queryWrapper);
       if (list == null) {
           throw new CustomException("购物车为空，不可下单");
       }

       //获得当前用户信息
       User user = userMapper.selectById(currentId);
       //查询地址信息
       AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
       if (addressBook == null) {
           throw  new CustomException("地址信息为空，不能下单");
       }


       long id = IdWorker.getId();//订单号，生成全局唯一ID
       //遍历购物车，获取总金额,并将订单明细数据整合起来
       List<OrderDetail> orderDetailList =new ArrayList<>();
       AtomicInteger amount = new AtomicInteger(0);//提供了一种线程安全的方式来操作整数类型的变量
       list.forEach(shoppingCart -> {
          OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(id);//设置订单号
            orderDetail.setNumber(shoppingCart.getNumber());
            orderDetail.setAmount(shoppingCart.getAmount());
            orderDetail.setDishId(shoppingCart.getDishId());
            orderDetail.setDishFlavor(shoppingCart.getDishFlavor());
            orderDetail.setSetmealId(shoppingCart.getSetmealId());
            orderDetail.setName(shoppingCart.getName());
            orderDetail.setImage(shoppingCart.getImage());
           amount.addAndGet(shoppingCart.getAmount()
                   .multiply(
                           new BigDecimal(shoppingCart.getNumber())
                   )
                   .intValue());
            orderDetailList.add(orderDetail);
       });

       //3.向订单表插入数据
       orders.setNumber(String.valueOf(id));//订单号
       orders.setStatus(2);//设置为待派送
       orders.setAmount(new BigDecimal(amount.get()));//计算总额
       orders.setOrderTime(new Date());
       orders.setCheckoutTime(new Date());
       orders.setUserId(currentId);
       orders.setUserName(user.getName());//由于用户没有设用户名，所以存放为空
       orders.setPhone(addressBook.getPhone());//收货人地址
       orders.setAddressBookId(orders.getAddressBookId());
       orders.setConsignee(addressBook.getConsignee());//设置收货人
        orders.setAddress(
                (addressBook.getProvinceName()==null?"":addressBook.getProvinceName())
                        + (addressBook.getCityName()==null?"":addressBook.getCityName())
                        + (addressBook.getDistrictName()==null?"":addressBook.getDistrictName())
                        + (addressBook.getDetail()==null?"":addressBook.getDetail())
        );//地址拼接
       ordersMapper.insert(orders);

       //4.向订单明细表插入数据
        orderDetailService.saveBatch(orderDetailList);

       //5.清空购物车
       shoppingCartService.cleanCart();
       return R.success("支付完成，等待派送");
    }
}
